<template>
  <div>
    <el-dialog
      v-model="visibleDialog"
      :title="props.title"
      width="800px"
      draggable
      @close="closeDialog"
      :close-on-click-modal="false"
      destroy-on-close
      align-center
    >
      <el-form
        ref="formRef"
        :model="formData"
        v-loading="loading1"
        label-width="90px"
        style="display: flex"
      >
        <el-row>
          <!--  <el-col :span="12">
            <el-form-item label="供应商编号">
              <el-input
                v-model="formData.partnerCode"
                placeholder="请选择"
                style="width: 100%"
                disabled
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商名称">
              <el-input
                v-model="formData.partnerName"
                placeholder="请选择"
                style="width: 100%"
                disabled
              >
              </el-input>
            </el-form-item>
          </el-col> -->

          <!-- 工厂号-->
          <el-col :span="12">
            <el-form-item label="物料编号">
              <el-input
                v-model="formData.materialCode"
                placeholder="请选择"
                style="width: 100%"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料名称">
              <el-input
                v-model="formData.materialName"
                placeholder="请选择"
                style="width: 100%"
                disabled
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="反馈日期">
              <el-date-picker
                :disabled="props.cellId != ''"
                v-model="formData.feedbackDate"
                :disabled-date="disabledDate"
                style="width: 100%"
                type="date"
                placeholder="请选择反馈日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划数量">
              <el-input
                v-model="formData.demandQuantity"
                placeholder="请选择计划数量"
                style="width: 100%"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="反馈数量">
              <el-input-number
                v-model="formData.feedbackQuantity"
                :min="1"
                :precision="0"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <!-- <el-col
            :span="12"
            v-if="props.title == '计划反馈' && formData.demandStatus == 1"
          >
            <el-form-item label="是否满足" prop="feedbackTotal">
              <el-radio-group
                v-model="formData.isSatisfy"
                :disabled="formData.demandStatus == 2"
                @change="radioChange"
              >
                <el-radio :label="1">满足</el-radio>
                <el-radio :label="0">不满足</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col> -->
        </el-row>
      </el-form>

      <!-- <div
        style="margin-bottom: 10px"
        v-if="formData.isSatisfy == 0 && props.title != '反馈信息'"
      >
        <el-button
          type="success"
          plain
          @click="handleAdd"
          :disabled="formData.demandStatus == 2"
          v-if="formData.isSatisfy == 0"
        >
          <i-ep-plus />
          新增
        </el-button>
      </div>
      <div>
        <div class="formTable" v-if="formData.isSatisfy == 0">
          <el-table
            :data="formData.details"
            :key="Math.random"
            border
            ref="formTableRef"
            class="associate-table"
          >
            <el-table-column
              label="序号"
              type="index"
              align="center"
              min-width="50"
            >
            </el-table-column>
            <el-table-column
              label="要货日期"
              props="memberName"
              align="center"
              min-width="150"
            >
              <template #default="{ $index, row }">
                <span>{{ dayjs(row.demandDate).format("YYYY/MM/DD") }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="供货日期"
              props="feedbackDate"
              min-width="150"
              align="center"
              style="padding-top: 15px"
            >
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.feedbackDate'"
                  label-width="0"
                >
                  <el-date-picker
                    v-model="row.feedbackDate"
                    v-if="props.title == '计划反馈'"
                    :disabled-date="disabledDate"
                    :disabled="formData.demandStatus != 1"
                    style="width: 100%"
                    type="date"
                    placeholder="请选择供货日期"
                    @change="handleDateChange"
                    format="YYYY/MM/DD"
                    value-format="YYYY-MM-DD"
                  />
                  <span v-else>{{ row.feedbackDate }}</span>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              label="可供应数量"
              props="feedbackTotal"
              min-width="150"
              align="center"
              style="padding-top: 15px"
            >
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.feedbackQuantity'"
                  :rules="rules.feedbackQuantity"
                  label-width="0"
                >
                  <el-input-number
                    v-if="props.title == '计划反馈'"
                    v-model="row.feedbackQuantity"
                    :min="1"
                    style="width: 100%"
                    :precision="0"
                    :disabled="formData.demandStatus != 1"
                  />
                  <span v-else>{{ row.feedbackQuantity }}</span>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              align="center"
              label="操作"
              v-if="props.title == '计划反馈'"
            >
              <template #default="scope">
                <el-button
                  type="danger"
                  link
                  @click.stop="handleDelete(scope.$index)"
                  :disabled="formData.demandStatus != 1"
                  ><i-ep-delete />
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div> -->
      <template #footer>
        <div class="dialog-footer" v-if="!loading1">
          <el-button type="primary" :loading="loading" @click="handleSubmit"
            >反馈确定</el-button
          >
          <!-- <el-button
            type="danger"
            :loading="loading"
            v-if="props.title == '修改计划反馈'"
            @click="revoke(props.cellId)"
            >反馈撤回</el-button
          > -->
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();
import dayjs from "dayjs";

const handleDateChange = (e) => {
  console.log(e);
};

defineOptions({
  name: "SRMREQUIREGOODSADDDIALOG1",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  id: {
    type: String,
    default: () => {
      return "";
    },
  },
  cellId: {
    type: String,
    default: () => {
      return "";
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  begirate: {
    type: String,
    default: () => {
      return "";
    },
  },
  endDate: {
    type: String,
    default: () => {
      return "";
    },
  },
});
const disabled = ref(false);
const loading1 = ref(false);
const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;

    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

// 如果有单元格id 说明是修改
watch(
  () => props.cellId,
  (newVal: any) => {
    if (newVal) {
      console.log("newVal", newVal);
      loading1.value = true;
      getCellList(newVal);
    }
  }
);

// 获取反馈信息
const getCellList = async (id) => {
  await request({
    url: `/mes/srmdemandschedule/getInfo/${id}`,
    method: "get",
  }).then((res) => {
    console.log("res.data", res.data);
    Object.assign(formData, { ...res.data });
    formData.feedbackDate = formData.demandDate; // 反馈日期
    formData.id = ""; // 反馈日期
    loading1.value = false;
  });
};

// 表单校验规则
const rules = reactive({
  plantId: [{ required: true, message: "未选择工厂", trigger: "change" }],
  partnerId: [{ required: true, message: "未选择供应商", trigger: "change" }],
  arriveDate: [
    {
      required: true,
      type: "date",
      message: "未选择到货日期",
      trigger: "change",
    },
  ],
  demandDate: [
    {
      required: true,
      message: "未选择要货日期",
      trigger: "change",
    },
  ],
  materialId: [{ required: true, message: "未选择物料", trigger: "blur" }],
  storageLocationName: [
    { required: true, message: "未选择要货地点", trigger: "change" },
  ],
  planQuantity: [
    { required: true, message: "未输入要货数量", trigger: "change" },
  ],
  feedbackDate: [{ required: true, message: "未选择", trigger: "change" }],
  dischargeHatchId: [
    { required: true, message: "未选择卸货口", trigger: "change" },
  ],
  purchasePlanNumber: [
    { required: true, message: "未选择采购协议", trigger: "change" },
  ],
  remarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  beginDate: [],
  endDate: [],
  filename: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  plantId: "",
  plantCode: "",
  plantName: "",
  partnerId: "",
  partnerCode: "",
  partnerName: "",
  dischargeHatchId: "",
  dischargeHatchCode: "",
  dischargeHatchName: "",
  materialId: "",
  materialCode: "",
  materialName: "",
  // 物料需求ID
  demandId: props.id,
  // 需求日期
  demandDate: "",
  // 需求数量
  feedbackQuantity: 0,
  // 需求日期（格式化）
  demandDateShow: "",
  // 当前计划数量
  demandQuantity: "",
  // 计划id
  planId: "",
  // 反馈日期
  feedbackDate: "",
  // 反馈总数量
  feedbackTotal: "",
  // 是否反馈确认
  demandStatus: 1,
  scheduleId: "",
  isSatisfy: 1,
  details: [],
});

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.plantId = "";
  formData.plantCode = "";
  formData.plantName = "";
  formData.partnerId = "";
  formData.partnerCode = "";
  formData.partnerName = "";
  formData.dischargeHatchId = "";
  formData.dischargeHatchCode = "";
  formData.dischargeHatchName = "";
  formData.materialId = "";
  formData.materialCode = "";
  formData.materialName = "";

  formData.demandId = props.id;
  // 需求日期
  formData.demandDate = "";
  // 需求数量
  formData.feedbackQuantity = 0;
  // 需求日期（格式化）
  formData.demandDateShow = "";
  // 计划id
  formData.planId = "";
  formData.isSatisfy = 1;
  disabled.value = false;
  formData.details = JSON.parse(JSON.stringify(details));
  formData.demandQuantity = "";
  formData.scheduleId = "";
  formData.demandStatus = 1;
}

const loading = ref(false);

// 禁用当前日期之前日期(不包含当天日期)
// const disabledDate = (time: Date) => {
//   return !(
//     time.getTime() <= dayjs(props.endDate) &&
//     time.getTime() >= dayjs(props.begirate)
//   );
// };

// 禁用当前日期之前日期(不包含当天日期)
const disabledDate = (time: Date) => {
  if (time.getTime() > dayjs(props.endDate).valueOf()) {
    return true;
  }
  if (time.getTime() < dayjs(props.begirate).valueOf()) {
    return true;
  }
  return false;
};
/** 订货计划保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/mes/srmdemandfeedback/feedback",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

// 撤销按钮
async function revoke(id: any) {
  ElMessageBox.confirm("确认撤销该数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await request({
      url: `/mes/srmdemandfeedback/retract/${id}`,
      method: "get",
    }).then((res) => {
      ElMessage.success("撤销成功！");
      closeDialog();
      emit("reset-table", formData.id);
    });
  });
}

/** 添加行 */

let details = {
  demandId: "",
  feedbackId: "",
  // 反馈id
  feedbackDate: "",
  // 需求日期
  demandDate: "",
  feedbackQuantity: 1,
  id: "",
};

const formTableRef = ref();
const handleAdd = () => {
  let sondata = [];
  details.demandDate = formData.demandDate;
  details.demandId = formData.demandId;
  sondata = JSON.parse(JSON.stringify(details));
  formData.details.push(sondata);
  scrollToBottom();
};

const scrollToBottom = () => {
  // /超过设置的高度出现滚动条，添加行定位到底部
  //     1.先拿到设置table的最大高度【滚动条的高度】的元素，获取元素的clientHeight
  //     2.在拿到table的所有行的高度的元素，获取元素的clientHeight
  //     3，当他们相减就是滚动条距离底部的间距，在设置scrollTop
  const el: any = document.querySelector(
    ".associate-table .el-scrollbar__wrap"
  );
  const el2: any = document.querySelector(
    ".associate-table .el-table__body tbody"
  );
  setTimeout(() => {
    const height = el2.clientHeight - el.clientHeight;
    if (height > 0) {
      el.scrollTop = height;
    }
  }, 200);
};

/** 删除行 */
const handleDelete = (index: any) => {
  formData.details.splice(index, 1);
};
// 点击是否满足
const radioChange = (e) => {
  if (e) {
    formData.details = [];
  }
};

onMounted(() => {});

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
</script>
<style scoped lang="scss">
.formTable {
  :deep(.el-form-item) {
    margin: 0 0 13px 0 !important;
    width: 100%;
  }
  :deep(.el-scrollbar__wrap) {
    max-height: 200px;
    overflow-y: auto;
  }
}

:deep(.el-dialog .formTable .el-table .el-form-item) {
  padding: 11px 0 0 0 !important;
}
:deep(.el-dialog .formTable .el-table .el-form-item__error) {
  font-size: 11px !important;
}

:deep(.el-dialog .formTable .el-table) {
  .el-table__body td.el-table__cell {
    // padding: 5px !important;
    padding: 0 !important;
  }
}
</style>
